package com.hand.wfive.fragment.sign

import android.app.Dialog
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.view.View
import android.widget.ImageView
import android.widget.TextView
import com.hand.wfive.util.bottomShow
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.contract.ActivityResultContracts
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.SimpleItemAnimator
import com.alibaba.android.arouter.launcher.ARouter
import com.doris.media.picker.model.MediaModel
import com.doris.media.picker.model.MediaPickerParameter
import com.doris.media.picker.result.contract.MediaPickerContract
import com.doris.media.picker.utils.MediaUtils
import com.doris.media.picker.utils.permission.MyPermissionsUtils
import com.hand.wfive.App
import com.hand.wfive.R
import com.hand.wfive.ad.AdFragment
import com.hand.wfive.adapter.SignLibraryAdapter
import com.hand.wfive.base.BaseFragment
import com.hand.wfive.entity.FileListModel
import com.hand.wfive.entity.FileModel
import com.hand.wfive.entity.Params
import com.hand.wfive.loginAndVip.ApiConfig
import com.hand.wfive.loginAndVip.LoginConfig
import com.hand.wfive.loginAndVip.UserManager
import com.hand.wfive.util.click.NoFastClickUtils
import com.hand.wfive.util.click.singleClick
import com.hand.wfive.util.oss.OssRequest
import com.hjq.permissions.Permission
import com.rxjava.rxlife.RxLife
import com.hand.wfive.activity.sign.MakeStampActivity
import com.hand.wfive.activity.sign.SignatureWriteActivity
import com.hand.wfive.base.Constant
import com.hand.wfive.dialog.MsgDialog
import com.hand.wfive.entity.SignLibEvent
import com.hand.wfive.util.FuncSwitchUtils
import com.hand.wfive.util.ShareUtils
import com.hand.wfive.util.oss.OssCallBack
import com.hand.wfive.view.InputDialog
import com.hand.wfive.view.dialog.MoreFileCenter
import com.hand.wfive.view.dialog.MoreFileSign
import com.lxj.xpopup.XPopup
import kotlinx.android.synthetic.main.fragment_sign_library_item.*
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import org.jetbrains.anko.find
import org.jetbrains.anko.support.v4.toast
import rxhttp.wrapper.param.RxHttp
import rxhttp.wrapper.param.asClass

class SignLibraryItemFragment : AdFragment() {

    companion object {
        fun load(type: String): BaseFragment {
            val fragment = SignLibraryItemFragment()
            fragment.arguments = Bundle()
            fragment.arguments?.putString(Params.type, type)
            return fragment
        }
    }

    private var mPage = 1
    private var mType = Params.fileTypeSign
    private lateinit var mAdapter: SignLibraryAdapter
    private lateinit var mTurnAdd: ActivityResultLauncher<Intent>
    private lateinit var mPickerImage: ActivityResultLauncher<MediaPickerParameter>

    override fun onAttach(context: Context) {
        super.onAttach(context)
        mType = arguments?.getString(Params.type) ?: mType

        mTurnAdd = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) {
            if (it.resultCode == RESULT_OK) {
                mPage = 1
                loadData()
            }
        }

        mPickerImage = registerForActivityResult(MediaPickerContract()) {
            if (it.isPicker) addStampImage(it.getFirst())
        }
    }

    override fun getLayoutId() = R.layout.fragment_sign_library_item

    override fun init() {
        registerEventBus()
    }

    override fun initKotlinWidget() {
        mAdapter = SignLibraryAdapter(mType)
        mAdapter.setOnItemClickListener { _, _, position ->
            if (position != 0) return@setOnItemClickListener
            if (NoFastClickUtils.isFastClick()) return@setOnItemClickListener
            if (mAdapter.itemCount >= 6) showVip()
            else fragmentAdClose()
        }
        mAdapter.addChildClickViewIds(R.id.iv_more)
        mAdapter.setOnItemChildClickListener { _, view, position ->
            if (NoFastClickUtils.isFastClick()) return@setOnItemChildClickListener
            showMoreDialog(position,view)
        }
        recycler_sign_library.layoutManager = GridLayoutManager(mContext, 2)
        (recycler_sign_library.itemAnimator as SimpleItemAnimator).supportsChangeAnimations = false
        recycler_sign_library.adapter = mAdapter

        mAdapter.loadMoreModule.isEnableLoadMore = true
        mAdapter.loadMoreModule.setOnLoadMoreListener {
            loadData()
        }

        loadData()
    }

    override fun fragmentAdClose() {
        super.fragmentAdClose()
        mBaseHandler.post {
            if (mType == Params.fileTypeSign) {
                // 添加签名
                mTurnAdd.launch(Intent(mContext, SignatureWriteActivity::class.java))
            } else {
                // 添加签章
                showAddStampDialog()
            }
        }
    }

    private fun showAddStampDialog() {
        val dialog = Dialog(mContext, R.style.CustomDialog)
        dialog.setContentView(R.layout.dialog_sign_library_add_stamp)
        dialog.find<TextView>(R.id.tv_album).singleClick {
            dialog.dismiss()
            mPickerImage.launch(MediaPickerParameter())
        }
        dialog.find<TextView>(R.id.tv_make).singleClick {
            dialog.dismiss()
            mTurnAdd.launch(Intent(mContext, MakeStampActivity::class.java))
        }
        dialog.find<ImageView>(R.id.iv_close).singleClick { dialog.dismiss() }
        dialog.show()
    }

    private fun addStampImage(mediaModel: MediaModel) {
        val model = FileModel()
        model.type = Params.fileTypeStamp
        model.fileName = mediaModel.name
        model.fileId = "${UserManager.getInstance().userId}/${Params.fileTypeStamp}/${
            System.currentTimeMillis()
        }${model.fileName.replace(",", "")}"
        model.filePath = mediaModel.path
        model.size = mediaModel.size
        showLoading()
        OssRequest.getInstance().uploadFile(model, object : OssCallBack {
            override fun onSuccess() {
                dismissTip()
                mAdapter.addData(model)
            }

            override fun onFailure(msg: String) {
                showNormalTip(msg.ifEmpty { "添加签章失败" })
            }
        })
    }

    private fun resetPage() {
        mPage--
        if (mPage < 1) mPage = 1
        mAdapter.loadMoreModule.loadMoreComplete()
    }

    private fun loadData() {
        RxHttp.postForm(ApiConfig.getUserFileList)
            .add("appid", LoginConfig.AppId)
            .add("userId", UserManager.getInstance().userId)
            .add("type", mType)
            .add("pageSize", 30)
            .add("page", mPage)
            .asClass<FileListModel>()
            .to(RxLife.toMain(this))
            .subscribe({
                if (it.code == ApiConfig.SUCCESSCODE) {
                    if (mPage == 1) {
                        val data = ArrayList<FileModel>()
                        data.add(FileModel())
                        if (it.data.records.isNotEmpty()) {
                            data.addAll(it.data.records)
                            mPage++
                        }
                        mAdapter.setNewInstance(data)
                        if (data.size == 1) {
                            mAdapter.loadMoreModule.loadMoreEnd(true)
                        } else {
                            mAdapter.loadMoreModule.loadMoreComplete()
                        }
                    } else if (it.data.records.isEmpty()) {
                        mAdapter.loadMoreModule.loadMoreEnd(true)
                    } else {
                        mAdapter.addData(it.data.records)
                        mPage++
                        mAdapter.loadMoreModule.loadMoreComplete()
                    }
                } else resetPage()
            }, {
                resetPage()
            })
    }

    private fun showMoreDialog(position: Int,view:View) {
        val model = mAdapter.getItem(position)
        XPopup.Builder(mContext)
                 .dismissOnBackPressed(false).hasShadowBg(false)
                 .atView(view)
                 .asCustom(MoreFileSign(mContext).addOnMoreFileSignCallBack {
                     when(it){
                         1->{
                             share(model)
                         }
                         2->{
                             delete(model)
                         }
                     }
                 }).show()


//        val dialog = Dialog(mContext, R.style.CustomDialog)
//        dialog.setContentView(R.layout.dialog_sign_library_more)
//        // 重命名
//        dialog.find<ImageView>(R.id.iv_rename).singleClick {
//            dialog.dismiss()
//            rename(model, position)
//        }
//        // 分享
//        dialog.find<ImageView>(R.id.iv_share).singleClick {
//            dialog.dismiss()
//            share(model)
//        }
//        // 删除
//        dialog.find<ImageView>(R.id.iv_delete).singleClick {
//            dialog.dismiss()
//            delete(model)
//        }
//        // 底部显示
//        dialog.bottomShow()
    }

    private fun rename(model: FileModel, position: Int) {
        InputDialog(mContext, "重命名", model.fileName, content = model.fileName) { dialog, value ->
            if (value.isEmpty()) {
                toast("请输入文件名！")
                return@InputDialog
            }
            if (value == model.fileName) {
                dialog.dismiss()
                return@InputDialog
            }
            dialog.dismiss()
            showLoadingTipC()
            OssRequest.getInstance().renameFile(model, value, object : OssCallBack {
                override fun onSuccess() {
                    dismissTip()
                    model.fileName = value
                    mAdapter.notifyItemChanged(position)
                }

                override fun onFailure(msg: String) {
                    showNormalTip(msg)
                }
            })
        }.show()
    }

    private fun share(model: FileModel) {
        MyPermissionsUtils.requestPermissionsTurn(
            this, "用于保存文件到手机以便分享",
            object : MyPermissionsUtils.HavePermissionListener {
                override fun havePermission() {
                    showLoadingTipC()
                    val suffix = model.fileId.substring(model.fileId.lastIndexOf("."))
                    val savePath = if (model.fileName.endsWith(suffix, true)) {
                        "${App.getContext().downloadPath}/${model.fileName}"
                    } else {
                        "${App.getContext().downloadPath}/${model.fileName}${suffix}"
                    }
                    OssRequest.getInstance().dowloadFile(
                        model.fileId, savePath, object : OssCallBack {
                            override fun onSuccess() {
                                dismissTip()
                                MediaUtils.refreshSystemMedia(mContext, savePath)
                                ShareUtils.sharePicture(mContext, savePath)
                            }

                            override fun onFailure(msg: String) {
                                showNormalTip(msg)
                            }
                        })
                }
            }, Permission.WRITE_EXTERNAL_STORAGE
        )
    }

    private fun delete(model: FileModel) {
        MsgDialog(
            mContext, "您确定删除此签名文件吗？","提示",
        ) {
            if (it == 1) {
                showLoadingTipC()
                OssRequest.getInstance().delCloudFile(model, object : OssCallBack {
                    override fun onSuccess() {
                        dismissTip()
                        mAdapter.remove(model)
                    }

                    override fun onFailure(msg: String) {
                        showNormalTip(msg)
                    }
                })
            }
        }.show()
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun doSignLibEvent(event: SignLibEvent) {
        if (mType == event.type) {
            mPage = 1
            loadData()
        }
    }
}